package com.heima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.heima.code.CodeMsg;
import com.heima.mapper.KsClassMapper;
import com.heima.mapper.UserMapper;
import com.heima.mapper.UserPlusMapper;
import com.heima.pojo.KsClass;
import com.heima.pojo.User;
import com.heima.pojo.utils.Result;
import com.heima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private KsClassMapper ksClassMapper;

    @Autowired
    private UserPlusMapper userPlusMapper;



    /**
     * 根据手机号查询用户信息
     * @param mobile
     * @return
     */
    @Override
    public Result findByMobile(String mobile) {
        //1.todo 根据手机查询用户是否存在
        User user = userMapper.selectByMobile(mobile);
        //2.todo 不存在则直接返回即可
        if(user == null){
            return new Result(0,"用户不存在","用户不存在");
        }
        //3.todo 存在
        if(user.getRoleId() == 2){//代表事学生
            KsClass byId = ksClassMapper.findById(user.getClassId());
            User student = userPlusMapper.selectById(user.getId());

            return  new Result(0,"操作成功","学生账户");
        }
        //4.todo 代表老师账户  查询所有的班级信息，返回即可
        List<KsClass> ksClasses = ksClassMapper.selectAll();

        return new Result(0,"老师账户",ksClasses);
    }

    @Override
    public Result loginIn(Integer classId,String name, String password) {
        Integer integer = userMapper.loginIn(name, password);
        List<User> userList = userMapper.findByClassId(classId);
        return new Result(integer>0 ? 0 : -1,integer>0 ? "操作成功" : "操作失败" , userList);
    }

    @Override
    public Result findByClassId(Integer classId) {

        List<User> users = userMapper.findByClassId(classId);
        return new Result(users != null ? CodeMsg.MSG_OK : CodeMsg.MSG_ERROR , users != null ? "操作成功" : "操作失败"  ,users);
    }

    @Override
    public Result addIntegral(Integer id,Integer integral) {
        User user = userMapper.findById(id);
        integral = integral + user.getIntegral();
        Integer integer = userMapper.addIntegral(id, integral);
        if (integer>0)
        return new Result(CodeMsg.MSG_OK , "操作成功","添加积分成功");

        return new Result(CodeMsg.MSG_ERROR , "操作失败","添加积分失败");
    }

    @Override
    public Result resetGScoreByGroupId(Integer classId) {
        User user = new User();
        user.setIntegral(0);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getClassId,classId);
        userPlusMapper.update(user,wrapper);
        return new Result(0,"操作成功","重置成功");
    }


}
